package com.fun_ordering.controller;

import com.aliyuncs.ram.model.v20150501.ChangePasswordRequest;
import com.fun_ordering.components.ApiResponse;
import com.fun_ordering.components.CodeComponents;
import com.fun_ordering.pojo.FoEmployee;
import com.fun_ordering.pojo.FoEmployeeExample;
import com.fun_ordering.service.FoEmployeeService;
import com.fun_ordering.service.LoginService;
import com.fun_ordering.util.JJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author 陈星
 * @date 2024/3/19 19:19
 */
@RestController
@RequestMapping("/allow")
public class LoginController extends BaseController{
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private FoEmployeeService foEmployeeService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/empLogin")
    //使用security登录验证
    public ApiResponse login(@RequestBody FoEmployee foEmployee){
        ApiResponse<String> response = loginService.login(foEmployee);
        System.out.println(response);
        FoEmployee foEmployee1 = decodeToken(response.getData());
        response.setMsg(foEmployee1.getEmpId()+"");
        return response;
    }

    @PostMapping("/register")
    //使用security登录验证
    public ApiResponse register(@RequestBody FoEmployee foEmployee){
        //账号是否可用
        //个人详细信息可以后续补齐
        //设置用户登录信息
        foEmployee.setEmpPosition(CodeComponents.POSITION_EMP);
        //用户状态，在职
        //是否删除
        foEmployee.setIsDelete(CodeComponents.DELETE_NO);
        //对注册密码信息进行加密
        foEmployee.setEmpPassword(passwordEncoder.encode(foEmployee.getEmpPassword()));
        //但凡写没有返回值的接口在其调用的方法上写上try catch
        try {
            loginService.register(foEmployee);
        } catch (Exception e) {
            return ApiResponse.failed("注册失败");
        }
        return ApiResponse.success("注册成功!!");
    }

    @PostMapping("/login2")
    //一般常用方法
    public ApiResponse login2(@RequestBody FoEmployee foEmployee){
        //先调运service查询登录人对应的数据
        FoEmployee realEmployee = loginService.login2(foEmployee.getEmpAccount(),foEmployee.getEmpPassword());
        //判断是否为空，不为空获取token登录验证存入redis
        if (!ObjectUtils.isEmpty(realEmployee)) {
            //将用户信息获取为token令牌
            String token = JJwtUtil.getJwtToken(realEmployee);
            //给redis模板中存入token
            stringRedisTemplate.opsForValue().set("employee:login:" + foEmployee.getEmpPassword(), token);
            stringRedisTemplate.expire("emoloyee:login:" + foEmployee.getEmpAccount(), 2, TimeUnit.HOURS);
            return ApiResponse.success(token);
        }else{
            return ApiResponse.failed("登录失败~");
        }
    }

    @PostMapping("/exit")
    public ApiResponse logout(){
        try {
            FoEmployee loginUser = getUser();
            loginService.logout(loginUser.getEmpAccount());
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.failed(null);
        }
        return ApiResponse.success("退出成功");
    }

    @PostMapping("/changePassword")
    public ApiResponse changePassword(@RequestBody ChangePasswordRequest changePasswordRequest) {

        // 获取当前登录用户
        FoEmployee loginUser = getUser();
        System.out.println(changePasswordRequest);
        // 根据用户账号查询用户信息
        FoEmployee existingUser = foEmployeeService.selectByOne(loginUser.getEmpAccount());
        if(existingUser == null) {
            return ApiResponse.failed("用户不存在");
        }

        // 验证旧密码是否匹配
        if (!passwordEncoder.matches(changePasswordRequest.getOldPassword(), existingUser.getEmpPassword())) {
            return ApiResponse.failed("旧密码不正确");
        }

        // 更新密码
        existingUser.setEmpPassword(passwordEncoder.encode(changePasswordRequest.getNewPassword()));
        foEmployeeService.update(existingUser);
        return ApiResponse.success("密码修改成功");
    }
}
